import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入 store
import store from '@/store'
// 导入 getLocal
import { getLocal } from '@/utils/local.js'
// 导入 auInfo api
import { auInfo } from '@/api/my.js'

Vue.use(VueRouter)

const routes = [
  // 重定向
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/home',
    component: () => import('@/views/home/home.vue'),
    // 重定向
    redirect: '/home/my',
    children: [
      {
        path: '/home/company',
        component: () => import('@/views/home/company/company.vue'),
        meta: {
          needLoign: false,
          needTab: true
        }
      },
      {
        path: '/home/question',
        component: () => import('@/views/home/question/question.vue'),
        meta: {
          needLoign: true,
          needTab: true
        }
      },
      {
        path: '/home/find',
        component: () => import('@/views/home/find/find.vue'),
        meta: {
          needLoign: false,
          needTab: true
        }
      },
      {
        path: '/home/my',
        component: () => import('@/views/home/my/my.vue'),
        meta: {
          needLoign: true,
          needTab: true
        }
      },
      {
        path: '/home/myInfo',
        component: () => import('@/views/home/my/myInfo.vue'),
        meta: {
          needLoign: true
        }
      }
    ]
  }
]
const router = new VueRouter({
  routes
})
// 前置守卫
router.beforeEach((to, from, next) => {
  // 判断要不要登录
  if (!to.meta.needLoign) {
    next()
  } else {
    // 判断有没有登录
    if (store.state.isLoign) {
      next()
    } else {
      // 判断有没有 token
      if (getLocal('token')) {
        // 发送请求
        auInfo().then(res => {
          // console.log(res)
          // 用户信息
          store.commit('setUserInfo', res.data.data)
          // 登录状态
          store.commit('setIsLoign', true)
          next()
        })
      } else {
        // 路由传值 把因为没登陆的页面地址传过去
        next('/login?redirect=' + to.fullPath)
      }
    }
  }
})

// 这个是 解决 重复访问同一路由报错的
// 获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
// 修改原型对象中的push方法 --> 统一加上了catch 接收错误
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
export default router
